import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    vueDevTools(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  server: {
    port: 3000, // 设置开发服务器端口
    host: true, // 允许外部访问
    open: true, // 自动打开浏览器
    proxy: {
      '/api': {
        target: 'https://hongcat.oss-cn-chengdu.aliyuncs.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
      '/aiapi': {
        target: 'http://47.109.177.78:6300',
        changeOrigin: true,
        ws: true, // 支持WebSocket
        timeout: 60000, // 60秒超时
        configure: (proxy, _options) => {
          proxy.on('error', (err, _req, _res) => {
            console.log('Dify API 代理错误:', err)
          })
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            console.log('发送 Dify API 请求:', req.method, req.url)
            // 添加 Authorization 请求头
            proxyReq.setHeader('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE3NTY4MDc1MzMsImlzcyI6InRpZ3Nob3AiLCJzdWIiOiIxMzI1ODM2NTQyMSIsImV4cCI6MTc1OTM5OTUzMywidXNlcm5hbWUiOiIxMzI1ODM2NTQyMSIsImlzQWRtaW4iOmZhbHNlLCJ1c2VySWQiOjd9.ZdjwTTd7h7jfAgJvDwe7lGoqtU1MEEziBDA6TpZFdE_t2RV6JyU9wKPkHmcCtSbAnx7DMU0QlhNkxeG7C4Y33w')
          })
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('接收 Dify API 响应:', proxyRes.statusCode, req.url)
          })
        }
      },
      '/dify-api': {
        target: 'http://47.109.177.78:5404',
        changeOrigin: true,
        ws: true,
        timeout: 60000,
        rewrite: (path) => path.replace(/^\/dify-api/, '/api'),
        configure: (proxy, _options) => {
          proxy.on('error', (err, _req, _res) => {
            console.log('New Dify API 代理错误:', err)
          })
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            console.log('发送 New Dify API 请求:', req.method, req.url)
            // 添加 Authorization 请求头
            proxyReq.setHeader('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE3NTY4MDc1MzMsImlzcyI6InRpZ3Nob3AiLCJzdWIiOiIxMzI1ODM2NTQyMSIsImV4cCI6MTc1OTM5OTUzMywidXNlcm5hbWUiOiIxMzI1ODM2NTQyMSIsImlzQWRtaW4iOmZhbHNlLCJ1c2VySWQiOjd9.ZdjwTTd7h7jfAgJvDwe7lGoqtU1MEEziBDA6TpZFdE_t2RV6JyU9wKPkHmcCtSbAnx7DMU0QlhNkxeG7C4Y33w')
          })
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('接收 New Dify API 响应:', proxyRes.statusCode, req.url)
          })
        }
      }
    }
  }
})
